//
//  RecordViewController.swift
//  TianTianBiTing
//
//  Created by Gox mac 2 on 2019/3/11.
//  Copyright © 2019 Gox_WallyDiao. All rights reserved.
//

import UIKit

class RecordViewController: TTBaseVC {
    let RecordCollectTableViewCellID = "RecordCollectTableViewCell"
    let RecordRecommendTableViewCellID = "RecordRecommendTableViewCell"
    var type = 11
    
    var listModelArr:[ListenListModel] = [ListenListModel]()
    var commendModelArr:[RecordCommendModel] = [RecordCommendModel]()
    
    private lazy var tableView: TTTableView = {
        let tableView = TTTableView.init(frame: FRAME_CGFloat(0, 127, SCREEN_WIDTH, SCREEN_HEIGHT - OFFSET_TOP - OFFSET_BOTTOM - 127), style: UITableView.Style.plain)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = WhiteBackColor
        tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
        tableView.showsVerticalScrollIndicator = false
        tableView.showsHorizontalScrollIndicator = false
        tableView.register(NIBNAME(RecordCollectTableViewCellID), forCellReuseIdentifier: RecordCollectTableViewCellID)
        tableView.register(NIBNAME(RecordRecommendTableViewCellID), forCellReuseIdentifier: RecordRecommendTableViewCellID)
        tableView.tableHeaderView = UIView.init(frame: FRAME_CGFloat(0, 0, SCREEN_WIDTH, 0))
        
        return tableView
    }()
    
    var record:RecordHeadView = {
        let view = RecordHeadView.init(frame: FRAME_CGFloat(0, 0, SCREEN_WIDTH, 75.5))
        return view
    }()
    
    var bottomView:UIView = {
        let view = UIView.init(frame: FRAME_CGFloat(0, 0, SCREEN_WIDTH, 70))

        let button = UIButton(type: UIButton.ButtonType.custom)
        button.frame = FRAME_CGFloat(SCREEN_WIDTH / 2 -  45, 20, 90, 30)
        button.setImage(IMAGE(name: "collectMore"), for: .normal)
        button.addTarget(self, action: #selector(moreBtnAction), for: .touchUpInside)
        view.addSubview(button)
        return view
    }()
    

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "记录"
        // Do any additional setup after loading the view.
        setTop()
        setCentre()
        setTableView()
        setCollectData()
    }
    

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        setData()
    }

}

//  MARK: - ###### 方法 ######
extension RecordViewController {
    func setTop() {
        record.dateBlock = { (num) in
            switch num {
            case 11:
                let vc = HistoryVc()
                ISLOGIN_PUSHVIEWCONTROLLER(vc)
            case 12:
                let vc = BuyVc()
                ISLOGIN_PUSHVIEWCONTROLLER(vc)
            case 13:
                TTAlertView.showMessage(message: "暂未开放，尽情期待！", second: 2)
//                let vc = CacheVc()
//                PUSHVIEWCONTROLLER(vc)
            case 14:
                TTAlertView.showMessage(message: "暂未开放，尽情期待！", second: 2)
            default:
                return
            }
            
        }
        self.view.addSubview(record)
    }
    
    func setCentre() {
        let centre = RecordCentreView.init(frame: FRAME_CGFloat(0, 88.5, SCREEN_HEIGHT, 40))
        centre.dateBlock = { (num) in
            self.type = num
            switch num {
            case 11:
                self.setCollectData()
            case 12:
                self.setCommendData()
            default:
                return
            }
        }
        self.view.addSubview(centre)
    }
    
    func setTableView() {
        self.view.addSubview(self.tableView)
    }
    
    func setBottomView() {
        self.tableView.tableFooterView = self.bottomView
    }
    
    func setNoBottomView() {
        self.tableView.tableFooterView = UIView.init()
    }
}

//  MARK: - ###### 方法 ######
extension RecordViewController {
    func setData() {
        RecordRequestModel.loadMyBuyData { (success, message, model) in
            if success && model != nil {
                if (model?.count)! > 0 {
                    self.record.headLabel1.text = "·\(model?.count ?? 0)"
                }
            }
        }
    }
    func setCollectData() {
        if !String.getUserIdToString() {
            let vc = LoginVc()
            PRESENTVIEWCONTROLLER(vc)
        }
        MTProgressHUD.show()
        HomeRequestModel.loadHistoryAndCollectData(programId:[String.getUserId(),2],parameters: ["startPoint":1,"maxPage":999]) { (success, message, model, page) in
            if success && model != nil {
                self.listModelArr = model!
//                for dic in model! {
//                    self.listModelArr.append(dic)
//                }
            }
            self.tableView.reloadData()
            if self.listModelArr.count == 0 {
                self.tableView.setNoData(nodata: true)
            } else {
                self.tableView.setNoData(nodata: false)
                self.setBottomView()
            }
            MTProgressHUD.hidded(true)
        }
    }
    
    func setCommendData() {
        if !String.getUserIdToString() {
            let vc = LoginVc()
            PRESENTVIEWCONTROLLER(vc)
        }
        MTProgressHUD.show()
        RecordRequestModel.loadRecordRequestData(parameters: ["userId":String.getUserId()]) { (success, message, model) in
            if success && model != nil {
                self.commendModelArr = model!
                //                for dic in model! {
                //                    self.listModelArr.append(dic)
                //                }
            }
            self.tableView.reloadData()
            if self.commendModelArr.count == 0 {
                self.tableView.setNoData(nodata: true)
            } else {
                self.tableView.setNoData(nodata: false)
            }
            MTProgressHUD.hidded(true)
            self.setNoBottomView()
        }
    }
    
    @objc func moreBtnAction() {
        let mainVC = TTTabBarController()
        AppDelegate.getAppDelegate().window?.rootViewController = mainVC
        mainVC.selectedIndex = 0
    }
    
    func toCollect(programId:Int) {
        HomeRequestModel.increaseHistoryAndCollections(parameters: ["userId":String.getUserId(),"status":2,"programId":programId,"h5Url":""]) { (success) in
            if success {
                self.setCommendData()
                TTAlertView.showMessage(message: "收藏成功")
            }

        }
    }
    func noCollect(programId:Int) {
        HomeRequestModel.delHistory(parameters: ["userId":String.getUserId(),"programId":programId,"h5Url":""]) { (success) in
            if success {
                self.setCommendData()
                TTAlertView.showMessage(message: "取消收藏")
            }
        }
    }
}

//  MARK: - ###### 协议 ######
extension RecordViewController: UITableViewDelegate, UITableViewDataSource, RecordCollectTableViewCellDelegate, RecordRecommendTableViewCellDelegate {
    func collectActionDel(cell: UITableViewCell) {
        let index:IndexPath = self.tableView.indexPath(for: cell) as! IndexPath
        let model = self.commendModelArr[index.row]
        if model.markStatus == 0 {
            self.noCollect(programId: model.id)
        } else {
            self.toCollect(programId: model.id)
        }
    }
    
    func findActionDel(cell: UITableViewCell) {
        let index:IndexPath = self.tableView.indexPath(for: cell) as! IndexPath
        let model =  self.listModelArr[index.row]
        
        let find = FindView.init(frame: FRAME_CGFloat(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT))
        find.modelList = self.listModelArr[index.row]
        find.dateBlock = { (num) in
            switch num {
            case 11:
                let vc = FindVc()
                vc.programId = model.categoryId
               ISLOGIN_PUSHVIEWCONTROLLER(vc)
            case 12:
                self.setCollectData()
            case 13:
                self.setCollectData()
            case 14:
                HomeRequestModel.loadResourcesData(parameters: ["flg":"go_download"]) { (success, message, urlStr) in
                    if success {
                        let newUrl = urlStr + "?srcUserId=\(String.getUserId())"
                        let share = ShareView.init(frame: FRAME_CGFloat(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT), title: model.title ?? "天天必听", des: model.describe ?? "分享免费听", url: newUrl ?? "https://itunes.apple.com/cn/app/天天必听/id1449930721", image: model.shareImageUrl ?? "http://source.blistening.cn/bt_source/ttbt/logo/logo.png")
                        UIApplication.shared.keyWindow?.addSubview(share)
                    }
                }
            default:
                return
            }
            
        }
        UIApplication.shared.keyWindow?.addSubview(find)
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch self.type {
        case 11:
            return listModelArr.count
        case 12:
            return commendModelArr.count
        default:
            return 0
        }
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 94
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch self.type {
        case 11:
            let cell = tableView.dequeueReusableCell(withIdentifier: RecordCollectTableViewCellID) as! RecordCollectTableViewCell
            cell.backgroundColor = UIColor.clear
            cell.selectionStyle = .none
            let model = self.listModelArr[indexPath.row]
            cell.delegate = self
            cell.leftImageView.sd_setImage(with: URL(string: StringIncludeChineseToString(model.shareImageUrl ?? "")), completed: nil)
            cell.titleLabel.text = model.title
            cell.desLabel.text = model.describe
            cell.newLabel.text = "\(model.totalSeason)集更新"
            cell.listenNumberlabel.text = "\(model.listenNum)"
            cell.tolLabel.text = "\(model.totalSeason)集"
            return cell
        case 12:
            let cell = tableView.dequeueReusableCell(withIdentifier: RecordRecommendTableViewCellID) as! RecordRecommendTableViewCell
            cell.backgroundColor = UIColor.clear
            cell.selectionStyle = .none
            let model = self.commendModelArr[indexPath.row]
            cell.delegate = self
            cell.leftImageView.sd_setImage(with: URL(string: StringIncludeChineseToString(model.shareImageUrl ?? "")), completed: nil)
            cell.titleLabel.text = model.title
            cell.desLabel.text = model.describe
            cell.newLabel.text = "\(model.totalSeason)集更新"
            cell.listenLabel.text = "\(model.listenNum)"
            cell.tolLabel.text = "\(model.totalSeason)集"
            if model.markStatus == 0 {
                cell.collectBtn.setTitleColor(RGB(230, 67, 64), for: .normal)
                cell.collectImage.image = IMAGE(name: "record已收藏")
            } else {
                cell.collectBtn.setTitleColor(RGB(130, 136, 136), for: .normal)
                cell.collectImage.image = IMAGE(name: "record收藏")
            }
            return cell
        default:
            return UITableViewCell.init()
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        switch self.type {
        case 11:
            let model = self.listModelArr[indexPath.row]
            let playVc = PlayVC()
            playVc.id = model.id
            ISLOGIN_PUSHVIEWCONTROLLER(playVc)
        case 12:
            let model = self.commendModelArr[indexPath.row]
            let playVc = PlayVC()
            playVc.id = model.id
            ISLOGIN_PUSHVIEWCONTROLLER(playVc)
        default:
            return
        }
    }
}
